
import { Component, OnInit, ElementRef, Renderer2, Input, ChangeDetectorRef } from '@angular/core';
import { DatePipe } from '@angular/common';
import { ModalController, NavController, AlertController } from '@ionic/angular';
import { CacheService } from '@services/cache.service';
import { DataService } from '@services/data.service';
import { MultipleSelectModal } from '@modals/multiple-select/multiple-select';
import { MyNoteService } from '@services/myNote.service';
import { ActivatedRoute, Router } from '@angular/router';
import { ModalContentPage } from './modal-content';
import { containsTree } from '@angular/router/src/url_tree';
class AlarmInfo {
    alarmId: string;
    alarmLevel: number;
    alarmTime: string;
    alarmTypeId: number;
    alarmTypeName: string;
    alarmValue: number;
    areaId: number;
    areaName: string;
    deviceId: number;
    deviceName: string;
    deviceParameterId: number;
    deviceParameterName: string;
    isMy: boolean;
    isRestore: boolean;
    isTruncate: boolean;
    lastCancelUserId: number;
    procState: number;
    projectId: number;
    projectName: string;
    restoreTime: string;
    roundCount: number;
    taskId: number;
    unit: string;
}
@Component({
    selector: 'page-alarm-detail',
    templateUrl: 'alarm-detail.html',
    styleUrls: ['alarm-detail.scss']
})
export class AlarmDetailPage implements OnInit {
    public alarmTaskSrc = 'assets/imgs/alarmTask/4-1.png';
    public alarmTaskRepairSrc = 'assets/imgs/alarmTask/4-1-repair.png';
    public alarmDatas = [];
    public alarmInfo;    // 任务头部信息
    public cancelReason; // 换人原因
    public alarmReason;  // 告警原因
    public procContent;  // 处理情况
    public processState = ['未开始', '已确认', '已到场', '已处理', '无维修', '已完成'];
    public iotProcessState = ['未开始', '已确认', '已到场', '已处理', '已完成'];
    public process: any = [];        // 当前流程
    public historyProcess = []; // 历史流程
    public task;
    public userId;
    public type; // 物联/设备告警
    public noChangeMan = true; // 是否换人
    public title; // 头部标题
    public multipleType: string;
    public url: string;
    public isLook: any; // 是否查看
    public callback: any;
    public noFinish: boolean = true; // 是否完成
    public multipleMode = {// 多选框
        'changePerson': {
            options: {
                title: '请选择换人原因',
                list: [
                    { value: 1, Remark: '道行不够' },
                    { value: 2, Remark: '缺工具材料' },
                    { value: 3, Remark: '有紧急安排' },
                    { value: 4, Remark: '其它' }
                ],
                attrName: 'Remark'
            },
            showRemark: false,
            onlyLastShowRemark: true,
            onlyOne: true,
            remarkLen: 40
        },
        'alarm': {
            options: {
                title: '请选择是否维修',
                list: [
                    { value: 1, Remark: '有维修' },
                    { value: 2, Remark: '无维修' },
                ],
                attrName: 'Remark'
            },
            showRemark: false,
            onlyOne: true,
        },
        1: {
            options: {
                title: '请选择掉线原因',
                list: [
                    { value: 1, Remark: '断电' },
                    { value: 2, Remark: '断网' },
                    { value: 3, Remark: '硬件故障' },
                    // { value: 4, Remark: '其它' }
                ],
                attrName: 'Remark'
            },
            // showRemark: false,
            // onlyLastShowRemark: true,
            onlyOne: true,
            // remarkLen: 40
        },
        2: {
            options: {
                title: '请选择电池电量异常原因',
                list: [
                    { value: 4, Remark: '电池电量低' },
                    { value: 5, Remark: '电量衰减过快' },
                    // { value: 3, Remark: '其它' }
                ],
                attrName: 'Remark'
            },
            onlyOne: true,
        },
        3: {
            options: {
                title: '请选择数据异常原因',
                list: [
                    { value: 6, Remark: '超出上下限' },
                    { value: 7, Remark: '突变' },
                    // { value: 3, Remark: '其它' }
                ],
                attrName: 'Remark'
            },
            // showRemark: false,
            // onlyLastShowRemark: true,
            onlyOne: true,
            // remarkLen: 40
        },
        4: {
            options: {
                title: '请选择网络不稳定原因',
                list: [
                    { value: 4, Remark: '丢包率过高' },
                    { value: 5, Remark: '网络延时过大' },
                    // { value: 3, Remark: '其它' }
                ],
                attrName: 'Remark'
            },
            // showRemark: false,
            // onlyLastShowRemark: true,
            onlyOne: true,
            // remarkLen: 40
        },
        5: {
            options: {
                title: '请选择数据资源不足原因',
                list: [
                    { value: 6, Remark: 'CPU使用率过大' },
                    { value: 7, Remark: '内存使用过高' },
                    // { value: 3, Remark: '其它' }
                ],
                attrName: 'Remark'
            },
            // showRemark: false,
            // onlyLastShowRemark: true,
            onlyOne: true,
            // remarkLen: 40
        },
        'notDo': {
            options: {
                title: '请选择搞不定原因',
                list: [
                    { value: 1, Remark: '道行不够' },
                    { value: 2, Remark: '缺工具材料' },
                    { value: 3, Remark: '有紧急安排' },
                    { value: 4, Remark: '其它' }
                ],
                attrName: 'Remark'
            },
            showRemark: false,
            onlyLastShowRemark: true,
            onlyOne: true,
            remarkLen: 40
        },

    };
    public historyArr = [];
    public state; // 参数

    constructor(
        public modalCtrl: ModalController,
        public navCtrl: NavController,
        public el: ElementRef,
        public renderer: Renderer2,
        public dataservice: DataService,
        public cache: CacheService,
        private datePipe: DatePipe,
        public alertCtrl: AlertController,
        private myNote: MyNoteService,
        private activatedRoute: ActivatedRoute,
        private router: Router,
        private changeDetectorRef: ChangeDetectorRef
    ) {
        this.userId = this.cache.userinfo.userId;
        this.state = this.router.getCurrentNavigation().extras.queryParams;
        if (this.state) {
            this.multipleType = this.state.alarmType;
            this.type = this.state.type;
            this.alarmInfo = this.state.data;
            this.title = this.state.title ? this.state.title : '告警详情';
            this.url = this.state.url;
            this.isLook = this.state.isLook;
            this.callback = this.state.callback;
            this.alarmDatas = [this.alarmInfo];
        }
    }

    ngOnInit() {
        this.noFinish = true;
        this.getTask(this.type);
    }

    // 获取任务当前任务流程
    getTask(isIot = false) {
        const data = this.alarmInfo;
        const params = isIot ? {
            alarmType: data.alarmType,
            type: data.type,
            businessType: 1,
            businessId: data.alarmId,
            projectId: data.projectId,
            createUserId: data.createUserId,
            createUserName: data.createUserName
        } : {
                deviceId: data.deviceId,
                deviceParameterId: data.deviceParameterCode,
                alarmTypeId: data.alarmTypeId,
                businessType: 2,
                businessId: data.alarmId,
                projectId: data.projectId,
            }
        // 是否存在流程ID
        if (data.taskId) {
            this.getTaskList();
            // 是否为只读
        } else if (!this.isLook) {
            this.dataservice.getProcessCreate(params, isIot).subscribe((res: any) => {
                if (res.success) {
                    this.getTaskList();
                }
            });
        }
    }

    // 获取任务历史任务流程
    getHistoryTask() {
        let reqBody; reqBody = {};
        if (this.alarmInfo.isRestore) {
            reqBody.alarmId = this.alarmInfo.alarmId;
        } else {
            reqBody.deviceId = this.alarmInfo.deviceId;
            reqBody.deviceParameterId = this.alarmInfo.deviceParameterId;
            reqBody.alarmTypeId = this.alarmInfo.alarmTypeId;
        }
        this.dataservice.getAlarmHistoryTask(reqBody).subscribe(res => {
            this.historyProcess = this.dealHistoryData(res.data);
            if (!this.alarmInfo.taskId) {
                this.process = this.historyProcess;
            }
        });
    }

    // 处理任务
    dealTask(reqBody) {
        this.dataservice.dealTask(reqBody).subscribe(res => {
            if (res.success) {
                this.stepSuccess();
            }
        });
    }
    // 物联运维处理任务
    iotDealTask(params) {
        this.dataservice.getProcessProc(params, true, this.type).subscribe((res: any) => {
            if (res.success) {
                this.getTaskList();
            }
        })
    }
    // 处理
    step(data, isRepair) {
        if (((this.isLook === false && data.procState !== 3 && this.alarmDatas[0].procState !== data.procState - 1))
            || (this.isLook === true && data.procState !== 3)
            || this.noChangeMan === false) {
            return;
        }

        if (data.procState === 3) {       // 处理
            data.createUserId = data.createUserId === '' ? this.userId : data.createUserId;
            this.navCtrl.navigateForward([this.url], {
                queryParams: {
                    title: '处理描述',
                    data: data,
                    contents: data.contents,
                    type: this.type,
                    alarmInfo: this.alarmInfo,
                    isAdd: this.alarmInfo.procState !== 2 ? false : true,
                    isLook: data.createUserId !== this.userId ? true : this.isLook,
                    callback: (res) => {
                        if (res) {
                            this.getTaskList();
                        }
                    }
                }
            });
        } else if (data.procState === 2) {  // 到场
            const parmes: any = {};
            if (this.type) {
                parmes.businessId = data.businessId;
                parmes.taskId = data.taskId;
                parmes.procState = data.procState;
                parmes.type = this.alarmInfo.type;
            } else {
                parmes.deviceId = this.alarmInfo.deviceId;
                parmes.deviceParameterId = this.alarmInfo.deviceParameterId;
                parmes.alarmTypeId = this.alarmInfo.alarmTypeId;
                parmes.taskId = data.taskId;
                parmes.procState = data.procState;
            }
            this.iotDealTask(parmes);
        } else if (data.procState === 4) {  // 有无维修
            this.showMultipleSelectModal(!isRepair ? this.multipleType : 'notDo', data);
        }
    }


    stepSuccess() {
        if (this.task.procState !== 5) {
            let arr; arr = [];     // 这个看似多余的变量，可以让界面不会闪的很严重
            this.task.procState++; // 流程状态+1
            this.alarmDatas[0].procState = this.task.procState;
            const obj = {
                procState: this.task.procState,
                procTime: this.datePipe.transform(new Date(), 'yyyy-MM-dd HH:mm:ss')
            };
            this.task.details.push(obj);
            arr = this.dealCurrentData(this.task); // 重新处理一遍数据
            this.process = arr;
            if (this.task.procState === 3) {
                this.task.alarmReason = this.alarmReason;
                this.task.procContent = this.procContent;
            } else if (this.task.procState === 4) {
                this.stepSuccess();
            }
        }
    }

    // 填写信息弹出框
    async showPrompt() {
        const prompt = await this.alertCtrl.create({
            header: '处理信息填写',
            inputs: [
                {
                    name: 'alarmReason',
                    placeholder: '处理原因',
                    value: this.task.alarmReason
                },
                {
                    name: 'procContent',
                    placeholder: '处理情况',
                    value: this.task.procContent
                },
            ],
            buttons: [
                {
                    text: '取消',
                    handler: data => {
                        console.log('Cancel clicked', data);
                    }
                },
                {
                    text: '确定',
                    handler: data => {
                        console.log('Saved clicked', data);
                        this.alarmReason = data.alarmReason;
                        this.procContent = data.procContent;
                        let reqBody; reqBody = {};
                        reqBody.TaskId = this.task.taskId;
                        reqBody.ProcState = 3;
                        reqBody.AlarmReason = this.alarmReason;
                        reqBody.ProcContent = this.procContent;
                        reqBody.DeviceId = this.alarmInfo.deviceId;
                        reqBody.DeviceParameterId = this.alarmInfo.deviceParameterId;
                        reqBody.AlarmTypeId = this.alarmInfo.alarmTypeId;
                        this.dealTask(reqBody);
                    }
                }
            ]
        });
        await prompt.present();
    }

    async showPromptOnlyRead() {
        const content = {
            alarmReason: this.alarmReason,
            procContent: this.procContent
        };
        const modal = await this.modalCtrl.create({
            component: ModalContentPage,
            componentProps: { content: content }
        });
        await modal.present();
    }


    // 换人
    changeMan() {
        let reqBody; reqBody = {};
        reqBody.deviceId = this.alarmInfo.deviceId;
        reqBody.deviceParameterId = this.alarmInfo.deviceParameterId;
        reqBody.alarmTypeId = this.alarmInfo.alarmTypeId;
        reqBody.cancelReason = this.cancelReason;
        if (this.alarmInfo.isRestore) {
            reqBody.alarmId = this.alarmInfo.alarmId;
        }
        this.dataservice.changeMan(reqBody).subscribe(res => {
            if (res.success) {
                this.process[this.task.procState - 1].cancelReason = this.cancelReason;
                this.noChangeMan = false;
                this.myNote.MyNotice('换人成功');
            }
        });
    }

    // 弹出选择框
    async showMultipleSelectModal(type, thisData?) {

        if (type === 'changePerson') {
            if (this.alarmDatas[0].finishState === 1) {
                return;
            }
        }


        const Modal = await this.modalCtrl.create({
            component: MultipleSelectModal,
            componentProps: this.multipleMode[type]
        });
        Modal.onDidDismiss().then(data => {
            const reasonData = data.data;
            const params: any = {
                taskId: this.alarmInfo.taskId,
                procState: type === 'changePerson' ? this.alarmInfo.procState : 4,
                contents: [{
                    contentTypeValue: reasonData.remark === '' ? reasonData.value[0].Remark : reasonData.remark,
                    contentDataType: type === 'notDo' ? 6 : type === 'changePerson' ? 7 : 5
                }],
                businessId: this.alarmInfo.alarmId,
                type: this.alarmInfo.type
            };
            if (!this.type) {
                params.deviceId = this.alarmInfo.deviceId;
                params.deviceParameterId = this.alarmInfo.deviceParameterCode;
                params.alarmTypeId = this.alarmInfo.alarmTypeId;
            }
            if (type === 'changePerson') {
                params.userId = this.userId;
                this.getIotProcessCancel(params);
            } else {
                this.getIotProcessFinsh(params);
            }

        });
        await Modal.present();
    }
    // 完成操作
    getIotProcessFinsh(params) {
        this.dataservice.getProcessFinish(params, this.type).subscribe((res: any) => {
            if (res.success) {
                this.getTaskList();
            }
        });
    }
    // 换人操作
    getIotProcessCancel(params) {
        this.dataservice.getProcessCancel(params, this.type).subscribe((res: any) => {
            if (res.success) {
                this.noChangeMan = false;
                this.getTaskList();
            }
        });
    }

    // 下拉刷新
    doRefresh(refresher) {
        this.process = [...this.historyArr, ...this.process];
        this.historyArr = [];

        setTimeout(() => {
            console.log('Async operation has ended');
            if (refresher) {
                refresher.complete();
            }
        }, 500);
    }

    // 将任务处理处理成html方便展示的格式[{},{},{}...]
    dealData(task) {
        let arr; arr = [];
        for (let i = 0; i < task.details.length; i++) {
            let obj; obj = {};
            obj.createUserName = task.createUserName;
            obj.createUserId = task.createUserId;
            obj.procState = task.details[i].procState;
            obj.procTime = task.details[i].procTime;
            obj.procStateName = this.processState[obj.procState];
            // 换人原因
            if (i === task.details.length - 1) {
                obj.cancelReason = task.cancelReason;
            } else {
                obj.cancelReason = '';
            }
            // 图片
            if ((task.details[i].procState === 4 || task.details[i].procState === 5) && task.isRepair) {
                obj.img = task.details[i].procState + '-2' + '-repair';
                if (task.details[i].procState === 4) {
                    obj.procStateName = '有维修';
                }
            } else {
                obj.img = task.details[i].procState + '-2';
            }
            arr.push(obj);
        }
        return arr;
    }

    iotDealData(task) {
        let historyArr = [], nowArr = [], nowTodoIndex;
        // 单个任务多个处理流程
        task.forEach((c, i, s) => {
            let cancelReason = '';
            // 单个流程多个处理节点
            c.details.forEach((c1) => {
                const obj: any = {};
                obj.businessId = c.businessId;
                obj.taskId = c.taskId;
                obj.createUserName = c.createUserName;
                obj.createUserId = c.createUserId;
                obj.procState = c1.procState;
                obj.procTime = c1.procTime;
                obj.procStateName = this.iotProcessState[obj.procState];
                obj.img = c1.procState + '-2';
                obj.contents = [];
                // 节点附属文件（1-文本，2-图片，3-音频，4-视频，5-掉线原因，6-无法解决原因，7-换人原因）
                c1.contents.forEach((c2) => {
                    const reason = {
                        5: this.alarmInfo.alarmTypeName + '原因',
                        6: '搞不定原因',
                        7: '换人原因'
                    };
                    if (c2.contentDataType === 7 || c2.contentDataType === 5 || c2.contentDataType === 6) {
                        obj.cancelReason = this.type ? `(${reason[c2.contentDataType]}:${c2.contentTypeValue})` : `(${c2.contentTypeValue})`;
                        if (c2.contentDataType === 5) {
                            obj.procStateName = '已搞定';
                        }
                        if (c2.contentDataType === 6) {
                            obj.img = c2.procState + '-2' + '-repair';
                            obj.procStateName = '搞不定';
                        }
                        if (c2.contentDataType === 7) {
                            cancelReason = obj.cancelReason;
                        }
                    } else {
                        obj.cancelReason = '';
                        obj.contents.push({
                            type: c2.contentDataType,
                            value: c2.contentTypeValue,
                            duration: c2.contentDataType === 3 ? c2.duration : 0
                        });
                    }

                });
                if (c1.procState !== -1) {
                    if (i === s.length - 1) {
                        nowArr = [...nowArr, obj];
                    } else {
                        historyArr = [...historyArr, obj];
                    }
                }
            });
            if (cancelReason !== '') {
                if (i === s.length - 1) {
                    nowArr[nowArr.length - 1].cancelReason = cancelReason;
                } else {
                    historyArr[historyArr.length - 1].cancelReason = cancelReason;
                }
            }
            if (c.finishState === 0) {// 当前流程为处理状态
                nowTodoIndex = c.procState;
                for (let i = nowTodoIndex + 1; i < 6; i++) {
                    const obj: any = {};
                    obj.type = this.alarmInfo.type;
                    obj.businessId = c.businessId;
                    obj.taskId = c.taskId;
                    obj.createUserName = '';
                    obj.createUserId = '';
                    obj.procState = i;
                    obj.procTime = '';
                    obj.cancelReason = '';
                    obj.procStateName = '';
                    obj.nowTodo = false;
                    if (i === nowTodoIndex + 1) { // 即将要做的流程
                        obj.img = i + '-1';
                        obj.nowTodo = true;
                    } else {// 未做的流程
                        obj.img = i + '-0';
                    }
                    nowArr = [...nowArr, obj];
                }
            } else if (c.finishState === 1 && i === s.length - 1) {// 当前流程为完成状态
                const isNotDo = c.details[c.procState - 1].contents.filter((item) => { return item.contentDataType === 6 })
                const obj: any = {};
                obj.type = this.alarmInfo.type;
                obj.businessId = c.businessId;
                obj.taskId = c.taskId;
                obj.createUserName = c.createUserName;
                obj.createUserId = c.createUserId;
                obj.procState = c.procState + 1;
                obj.procTime = c.finishTime;
                obj.cancelReason = '';
                obj.procStateName = '已完成';
                obj.nowTodo = false;
                obj.img = isNotDo.length > 0 ? '5-2-repair' : '5-2';
                nowArr = [...nowArr, obj];
                this.noFinish = false;
            }
        });
        this.historyArr = historyArr;
        return nowArr;
    }
    // 每次流程操作都要重新获取流程列表
    getTaskList() {
        this.dataservice.getProcessGetTask({ bussinessId: this.alarmInfo.alarmId }, this.type).subscribe((res: any) => {
            if (res.success) {
                const procState = res.data[res.data.length - 1].procState;
                const finishState = res.data[res.data.length - 1].finishState;
                const taskId = res.data[res.data.length - 1].taskId;
                this.alarmDatas[0].procState = procState;
                this.alarmDatas[0].handleType = this.iotProcessState[procState];
                this.alarmDatas[0].finishState = finishState;
                this.alarmDatas[0].taskId = taskId;
                this.alarmInfo.taskId = taskId;
                this.process = this.dealCurrentData(res.data, 'iot');
            }
        });
    }

    // 补全当前节点detail中没有处理的节点
    dealCurrentData(task, type = 'alarm') {
        let arr = []; const nowTodoIndex = 0;
        if (type !== 'alarm') {
            arr = this.iotDealData(task);
            console.log('任务数组TaskArr:' + JSON.stringify(arr));
        } else {
            arr = this.dealData(task);
            const len = arr.length;
            for (let i = len + 1; i <= 5; i++) {
                let obj; obj = {};
                obj.createUserName = '';
                obj.createUserId = '';
                obj.procState = i;
                obj.procTime = '';
                obj.cancelReason = '';
                obj.procStateName = '';
                obj.nowTodo = false;
                if (i - task.procState === 1) { // 即将要做的流程
                    obj.img = i + '-1';
                    obj.nowTodo = true;
                } else if (i - task.procState > 1) { // 未做的流程
                    obj.img = i + '-0';
                }
                arr.push(obj);
            }
        }
        return arr;
    }

    // 处理历史数据
    dealHistoryData(tasks) {
        let arr; arr = [];
        for (let i = 0; i < tasks.length; i++) {
            arr = arr.concat(this.dealData(tasks[i]));
        }
        return arr;
    }

    // 视频
    watchVideo(data) {

    }

    goBack() {
        this.navCtrl.pop();
        const callbackFunc = this.callback;
        callbackFunc();
    }
}

